package com.ruoyi.web.controller.system;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.dto.WcImgPathEx;
import com.ruoyi.system.service.*;
import com.ruoyi.web.dto.HistoryProcess;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.client.RestTemplate;

import javax.xml.ws.ResponseWrapper;

/**
 * 订单发起Controller
 *
 * @author ruoyi
 * @date 2020-01-20
 */
@Controller
@RequestMapping("/system/wcorder")
public class WcComOrderController extends BaseController {
    private String prefix = "system/wcorder";

    @Autowired
    private IWcComOrderService wcComOrderService;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private IWcBasicInfoService wcBasicInfoService;

    @Autowired
    private IWcCarInfosService wcCarInfosService;

    @Autowired
    private IWcWorkInfoService wcWorkInfoService;

    @Autowired
    private IWcDanbrinfoService wcDanbrinfoService;

    @Autowired
    private IWcImgPathService wcImgPathService;

    void writeToLocal(String destination, InputStream input) throws IOException {
        int index;
        byte[] bytes = new byte[1024];
        FileOutputStream downloadFile = new FileOutputStream(destination);
        while ((index = input.read(bytes)) != -1) {
            downloadFile.write(bytes, 0, index);
            downloadFile.flush();
        }
        downloadFile.close();
        input.close();
    }

    InputStream doLoad(String address) {
        InputStream in = null;
        try {
            URL url = new URL(address);
            URLConnection urlConnection = url.openConnection();
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;

            // true -- will setting parameters
            httpURLConnection.setDoOutput(true);
            // true--will allow read in from
            httpURLConnection.setDoInput(true);
            // will not use caches
            httpURLConnection.setUseCaches(false);
            // setting serialized
            httpURLConnection.setRequestProperty("Content-type", "application/x-java-serialized-object");
            // default is GET
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setRequestProperty("connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("Charsert", "UTF-8");
            // 1 min
            httpURLConnection.setConnectTimeout(60000);
            // 1 min
            httpURLConnection.setReadTimeout(60000);

            // connect to server (tcp)
            httpURLConnection.connect();

            in = httpURLConnection.getInputStream();
        } catch(Exception e){
            e.printStackTrace();
            try {
                if(in != null){
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return in;
    }

    void zip(ZipOutputStream out, File f, String base) throws Exception
    {
        if (f.isDirectory()) {
            File[] files = f.listFiles();
            base = (base.length() == 0 ? "" : base + "/");
            for (int i = 0; i < files.length; i++) {
                zip(out, files[i], base + files[i].getName());
            }
        } else {
            out.putNextEntry(new ZipEntry(base));
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
            int c;

            while ((c = in.read()) != -1) {
                out.write(c);
            }
            in.close();
        }
    }

    @GetMapping("/export2zip")
    @ResponseBody
    public AjaxResult export2zip(String ordernum) throws IOException {
        String zipFilePath = Global.getDownloadPath() + ordernum;
        File dir = new File(zipFilePath);
        if (!dir.exists()) {// 判断目录是否存在
            dir.mkdir();
        }

        WcImgPath wcImgPath = new WcImgPath();
        wcImgPath.setOrderid(ordernum);
        List<WcImgPath> list5 = wcImgPathService.selectWcImgPathList(wcImgPath);
        if(list5 != null && list5.size() > 0) {
            List<WcImgPathEx> list = wcImgPathService.genImageList(list5);
            for (WcImgPathEx wcImgPathEx: list
                 ) {
                int count = 0;
                for(String str : wcImgPathEx.getImageList()) {
                    String extName = ".jpg"; //str.split(".")[1];
                    String newFileName = wcImgPathEx.getTypeName() + "_" + ++count + extName;
                    System.out.println(newFileName);

                    InputStream is = doLoad(str);
                    if(is != null) {
                        writeToLocal(zipFilePath + File.separator + newFileName, is);
                    }
                }
            }

        }

        Map<String, Object> map = new HashMap<String, Object>();

        WcCarInfos wcCarInfos = new WcCarInfos();
        wcCarInfos.setOrderid(ordernum);
        List<WcCarInfos> list2 = wcCarInfosService.selectWcCarInfosList(wcCarInfos);
        if(list2 != null && list2.size() > 0) {
            wcCarInfos = list2.get(0);
            map.put("brand", wcCarInfos.getBrand());
            map.put("spd", wcCarInfos.getSpd());
            map.put("pail", wcCarInfos.getPail());
            map.put("colour", wcCarInfos.getColour());
            map.put("zdj", wcCarInfos.getZdj());
        }

        WcBasicInfo wcBasicInfo = new WcBasicInfo();
        wcBasicInfo.setOrderid(ordernum);
        List<WcBasicInfo> list = wcBasicInfoService.selectWcBasicInfoList(wcBasicInfo);
        if(list != null && list.size() > 0) {
            wcBasicInfo = list.get(0);
            map.put("sqdke", wcBasicInfo.getSqdke());
            map.put("dealer", wcBasicInfo.getDealer());
            map.put("ckname", wcBasicInfo.getCkname());
            map.put("ckphone", wcBasicInfo.getCkphone());
            map.put("name", wcBasicInfo.getName());
            map.put("idnum", wcBasicInfo.getIdnum());
            map.put("phone", wcBasicInfo.getPhone());
            map.put("jzdz", wcBasicInfo.getJzdz());
            map.put("hkyh", wcBasicInfo.getHkyh());
            map.put("hkcar", wcBasicInfo.getHkcar());
            map.put("jtrk", wcBasicInfo.getJtrk());

        }

        WcWorkInfo wcWorkInfo = new WcWorkInfo();
        wcWorkInfo.setOrderid(ordernum);
        List<WcWorkInfo> list3 = wcWorkInfoService.selectWcWorkInfoList(wcWorkInfo);
        if(list3 != null && list3.size() > 0) {
            wcWorkInfo = list3.get(0);
            map.put("compantname", wcWorkInfo.getCompantname());
            map.put("cptdress", wcWorkInfo.getCptdress());
            map.put("cptphone", wcWorkInfo.getCptphone());
            map.put("grsr", wcWorkInfo.getGrsr());
            map.put("xrzw", wcWorkInfo.getXrzw());
            map.put("gzqh", wcWorkInfo.getGzqh());
            map.put("gzyb", wcWorkInfo.getGzyb());
            map.put("hjgl", wcWorkInfo.getHjgl());
        }

        WcDanbrinfo wcDanbrinfo = new WcDanbrinfo();
        wcDanbrinfo.setOrdernum(ordernum);
        List<WcDanbrinfo> list4 = wcDanbrinfoService.selectWcDanbrinfoList(wcDanbrinfo);
        if(list4 != null && list4.size() > 0) {
            wcDanbrinfo = list4.get(0);
            map.put("zhixqsxm", wcDanbrinfo.getZhixqsxm());
            map.put("zhxqsdh", wcDanbrinfo.getZhxqsdh());
            map.put("pengyxm", wcDanbrinfo.getPengyxm());
            map.put("pengysj", wcDanbrinfo.getPengysj());

        }

        String tempdir = System.getProperty("java.io.tmpdir") + System.currentTimeMillis() + ".xlsx";

        try {
            InputStream inputStream = new ClassPathResource("客户信息申请表.xlsx").getInputStream();
            writeToLocal(tempdir, inputStream);

        } catch (Exception e) {
            throw new BusinessException("读取模板失败");
        }

        String src = tempdir;
        String dest = zipFilePath + "/客户申请表.xlsx"; //Global.getDownloadPath() + "客户申请表.xlsx";

        TemplateExportParams params = new TemplateExportParams(src);

        // 遍历map判空赋值空字符串
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
            if(entry.getValue() == null)
                map.put(entry.getKey(), "");
        }


        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        if(workbook != null) {
            OutputStream out = null;
            try
            {
                out = new FileOutputStream(dest);
                workbook.write(out);

                // 打包zip文件
                ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(Global.getDownloadPath() + ordernum +".zip"));
                zip(zos, new File(zipFilePath), "");
                zos.close();

                return AjaxResult.success(ordernum +".zip");
            }
            catch (Exception e)
            {
                throw new BusinessException("导出zip失败，请联系网站管理员！");
            }
            finally
            {
                if (workbook != null)
                {
                    try
                    {
                        workbook.close();
                    }
                    catch (IOException e1)
                    {
                        e1.printStackTrace();
                    }
                }
                if (out != null)
                {
                    try
                    {
                        out.close();
                    }
                    catch (IOException e1)
                    {
                        e1.printStackTrace();
                    }
                }
            }
        }

        return null;
    }

    @GetMapping("/myHistoryProcess")
    @ResponseBody
    public List<Map<String, Object>> myHistoryProcess(String userId) {
        HistoryProcess obj = this.restTemplate.getForObject("http://localhost:8088/wcComOrder/myHistoryProcess?userId=" + userId, HistoryProcess.class);
        if(obj != null && obj.getSuccess())
            return obj.getData();

        return new ArrayList<>();
    }

    @RequiresPermissions("system:wcorder:view")
    @GetMapping()
    public String wcorder() {
        return prefix + "/wcorder";
    }

    /**
     * 查询订单发起列表
     */
    @RequiresPermissions("system:wcorder:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WcComOrder wcComOrder) {
        startPage();
        List<WcComOrder> list = wcComOrderService.selectWcComOrderList(wcComOrder);

        return getDataTable(list);
    }


    /**
     * 导出订单发起列表
     */
    @RequiresPermissions("system:wcorder:export")
    @Log(title = "订单发起", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(WcComOrder wcComOrder) {
        List<WcComOrder> list = wcComOrderService.selectWcComOrderList(wcComOrder);
        ExcelUtil<WcComOrder> util = new ExcelUtil<WcComOrder>(WcComOrder.class);
        return util.exportExcel(list, "wcorder");
    }

    /**
     * 新增订单发起
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存订单发起
     */
    @RequiresPermissions("system:wcorder:add")
    @Log(title = "订单发起", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(WcComOrder wcComOrder) {
        return toAjax(wcComOrderService.insertWcComOrder(wcComOrder));
    }

    /**
     * 修改订单发起
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        WcComOrder wcComOrder = wcComOrderService.selectWcComOrderById(id);
        mmap.put("wcComOrder", wcComOrder);
        return prefix + "/edit";
    }

    /**
     * 修改保存订单发起
     */
    @RequiresPermissions("system:wcorder:edit")
    @Log(title = "订单发起", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(WcComOrder wcComOrder) {
        return toAjax(wcComOrderService.updateWcComOrder(wcComOrder));
    }

    /**
     * 删除订单发起
     */
    @RequiresPermissions("system:wcorder:remove")
    @Log(title = "订单发起", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(wcComOrderService.deleteWcComOrderByIds(ids));
    }
}
